package com.itobase.questionnaire.config;

import com.itobase.questionnaire.util.Message;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;


/**
 * @author liucong
 * @date 2018/7/23
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    private Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 全局异常处理
     *
     * @param e Exception
     * @return message
     */
    @ExceptionHandler(Exception.class)
    public Message handlerException(Exception e) {

        logger.error(e.getMessage(), e);

        return Message.createErr(e.getMessage());
    }


    /**
     * 处理参数校验中抛出的异常
     *
     * @param e 参数校验异常
     * @return message
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Message handleMethodException(MethodArgumentNotValidException e) {
        logger.error(e.getMessage(), e);

        return Message.createErr(e.getBindingResult().getAllErrors().get(0).getDefaultMessage());
    }
}
